package com.atguigu.app.func;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import com.atguigu.utils.DruidDSUtil;
import com.atguigu.utils.JdbcUtil;
import com.atguigu.utils.JedisUtil;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {

    public static JSONObject getDimInfo(Connection connection, String tableName, String key) throws Exception {

        //查询Redis中数据
        Jedis jedis = JedisUtil.getJedis();
        String redisKey = "DIM:" + tableName + ":" + key;
        String dimInfoJson = jedis.get(redisKey);
        if (dimInfoJson != null) {
            //重置过期时间
            jedis.expire(redisKey, 24 * 3600);
            jedis.close();
            return JSON.parseObject(dimInfoJson);
        }

        //拼接SQL语句
        String querySql = "select * from " + GmallConfig.PHOENIX_DB + "." + tableName + " where id='" + key + "'";

        //获取数据
        List<JSONObject> queryList = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);

        //将数据写到Redis
        JSONObject dimInfo = queryList.get(0);
        jedis.set(redisKey, dimInfo.toJSONString());
        jedis.expire(redisKey, 24 * 3600);
        jedis.close();

        //返回结果
        return dimInfo;
    }

    public static void main(String[] args) throws Exception {

        DruidDataSource druidDataSource = DruidDSUtil.getDruidDataSource();
        DruidPooledConnection connection = druidDataSource.getConnection();

        long start = System.currentTimeMillis();
        JSONObject dimInfo = getDimInfo(connection, "DIM_BASE_CATEGORY1", "51"); //171  166  154  167
        long end = System.currentTimeMillis();
        JSONObject dimInfo2 = getDimInfo(connection, "DIM_BASE_CATEGORY1", "51");//9    11   12    9    1  0  1
        long end2 = System.currentTimeMillis();

        System.out.println(dimInfo);
        System.out.println(dimInfo2);
        System.out.println(end2 - end);

        connection.close();
        druidDataSource.close();
    }
}
